package org.homeworkteam.filter;

import com.alibaba.fastjson.JSON;
import org.homeworkteam.dto.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1. 白名单
        String url = request.getURI().getPath();
        String[] whiteList = {"/login","/register","/code","resetToken"};
        for (String white :
                whiteList) {
            if (url.contains(white)){
                return chain.filter(exchange);//这里放过，走下一个过滤器       设计模式：过滤器设计模式(链式设计模式)
            }
        }
        //2. 是否携带token
        List<String> lists = request.getHeaders().get("token");
        if (lists == null || lists.size() <= 0){
            //没有token
            return getNoAuth(response,"没有token");
        }
        String token = lists.get(0);
        //3. 判断token是否有效
        boolean re = redisTemplate.hasKey(token);
        if (!re){
            //无效token
            return getNoAuth(response,"无效的token");
        }
        //4. 权限是否足够     siro     spring sercurity
        return chain.filter(exchange);
    }

    public Mono<Void>  getNoAuth(ServerHttpResponse response,String msg){
        //没有token  友好提示   Result  code=401 message
        ResponseData result = new ResponseData(401,msg,null,0);
        String json = JSON.toJSONString(result);

        response.setStatusCode(HttpStatus.UNAUTHORIZED);  //默认200  401表示没有权限或授权
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
